package bme.andraskindler.treenventory.activity;

import java.util.Set;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import bme.andraskindler.treenventory.TreenventoryApplication;
import bme.andraskindler.treenventory.R;
import bme.andraskindler.treenventory.provider.BluetoothService;

/**
 * @author andraskindler
 * Ez az osztály a Bluetooth kapcsolódás felhasználói felületéért és a kapcsolódó funkciókért felel. Egy listát jelenít meg az elérhető készülékekkel.
 */
/**
 * @author andraskindler
 *
 */
/**
 * @author andraskindler
 * 
 */
@SuppressLint("NewApi")
public class BluetoothActivity extends Activity {

	// request codes
	private static final int REQUEST_ENABLE_BT = 101;

	private BluetoothAdapter mAdapter;
	private RelativeLayout mLayout;
	private ListView mListPaired, mListNew;
	private TextView mFooter;

	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;

	// Message types sent from the BluetoothChatService Handler
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;
	public static final int MESSAGE_REQUEST_PHOTO = 6;
	public static final int MESSAGE_SEND_PHOTO = 7;

	// Key names received from the BluetoothChatService Handler
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLayout = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_settings, null);
		setContentView(mLayout);

		if (TreenventoryApplication.getCurrentApiVersion() > android.os.Build.VERSION_CODES.HONEYCOMB) {
			final ActionBar actionbar = getActionBar();
			actionbar.setDisplayHomeAsUpEnabled(true);
		}

		mFooter = (TextView) mLayout.findViewById(R.id.footer_tv_title);
		mFooter.setText(TreenventoryApplication.getInstance().getConnectedDeviceName());

		mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.list_item_device_name);
		mListPaired = (ListView) mLayout.findViewById(R.id.settings_lv_paired);
		mListPaired.setAdapter(mPairedDevicesArrayAdapter);
		mListPaired.setOnItemClickListener(mOnItemClickListener);

		mFooter = (TextView) mLayout.findViewById(R.id.footer_tv_title);

		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.list_item_device_name);
		mListNew = (ListView) mLayout.findViewById(R.id.settings_lv_new);
		mListNew.setAdapter(mNewDevicesArrayAdapter);

		setupConnection();
	}

	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			mAdapter.cancelDiscovery();

			String info = ((TextView) view).getText().toString();
			String address = info.substring(info.length() - 17);
			System.out.println(address);

			BluetoothDevice device = mAdapter.getRemoteDevice(address);
			TreenventoryApplication.getInstance().getmService().connect(device, true);
			mFooter.setText(TreenventoryApplication.getInstance().getConnectedDeviceName());
		}
	};

	/**
	 * A Bluetooth szolgáltatás iniciálásáért és a már párosított készülékekért felel. Először megvizsgálja, hogy elérhető-e egyáltalán a Bluetooth kapcsolat a telefonban (azaz van-e benne Bluetooth chip). Ezután megnézi, hogy az be van-e kapcsolva, ha nincs, egy StartActivitForResulttal megkéri a felhasználót az aktiválásra. Ha minden megfelelő, feltölti a listát a párosított készülékekkel, majd elindítja a {@startDiscovery()} függvényt.
	 */
	private void setupConnection() {
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mAdapter == null) {
			Toast.makeText(TreenventoryApplication.getInstance(), "a készülék nem támogatja a Bluetooth adatátvitelt", Toast.LENGTH_SHORT).show();
			finish();
		}
		if (!mAdapter.isEnabled()) {
			startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT);
		} else {
			Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
			if (pairedDevices.size() > 0) {
				for (BluetoothDevice device : pairedDevices) {
					mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
				}
			} else {
				mPairedDevicesArrayAdapter.add("nem található párosított készülék");
			}

			if (TreenventoryApplication.getInstance().getmService() != null) {
				if (TreenventoryApplication.getInstance().getmService().getState() == BluetoothService.STATE_NONE) {
					TreenventoryApplication.getInstance().getmService().start();
				}
			}

			startDiscovery();
		}
	}

	/**
	 * 
	 * Ez a függvény az elérhető (látható) Bluetooth-eszközök feltérképezését indítja el egy intentfilter és egy broadcastreceiver segítségével.
	 */
	private void startDiscovery() {
		setProgressBarIndeterminateVisibility(true);
		setTitle("eszközök keresése");

		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		this.registerReceiver(mReceiver, filter);

		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);

		if (mAdapter.isDiscovering()) {
			mAdapter.cancelDiscovery();
		}

		mAdapter.startDiscovery();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			if (resultCode == RESULT_OK) {
				setupConnection();
				System.out.println("bluetooth is on");
			}
			break;
		default:
			break;
		}
	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
				}
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
				if (mNewDevicesArrayAdapter.getCount() == 0) {
					mNewDevicesArrayAdapter.add("nem található eszköz");
				}
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (mAdapter != null) {
			mAdapter.cancelDiscovery();
		}

		this.unregisterReceiver(mReceiver);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
